package com.example.icongyou;

import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;

public class CreateCourseFragment extends Fragment {

    private EditText etCourseTitle, etCourseDescription;
    private ImageButton btnBack;
    private Button  btnAddChapter, btnCancel, btnSaveCourse;
    private LinearLayout chapterContainer;
    private TextView tvTime;

    // 保存LayoutInflater，用于动态添加View
    private LayoutInflater fragmentInflater;

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        // 核心变化 1: 使用 inflater 来绑定布局
        View view = inflater.inflate(R.layout.fragment_create_course, container, false);
        fragmentInflater = inflater;

        initViews(view); // 核心变化 2: 传递根视图
        setupClickListeners();
        updateTime();

        return view;
    }

    private void initViews(View view) {
        // 核心变化 3: 使用传入的 View 来查找子视图
        etCourseTitle = view.findViewById(R.id.et_course_title);
        etCourseDescription = view.findViewById(R.id.et_course_description);
        btnBack = view.findViewById(R.id.btn_back);
        btnAddChapter = view.findViewById(R.id.btn_add_chapter);
        btnCancel = view.findViewById(R.id.btn_cancel);
        btnSaveCourse = view.findViewById(R.id.btn_save_course);
        chapterContainer = view.findViewById(R.id.chapter_container);
        tvTime = view.findViewById(R.id.tv_time);

        setupSampleData();
    }

    private void setupSampleData() {
        // 保持不变
    }

    private void setupClickListeners() {
        // 返回按钮
        btnBack.setOnClickListener(v -> closeFragmentOrActivity());


        // 添加章节
        btnAddChapter.setOnClickListener(v -> addNewChapter());

        // 取消
        btnCancel.setOnClickListener(v -> closeFragmentOrActivity());

        // 保存课程
        btnSaveCourse.setOnClickListener(v -> saveCourse());
    }

    /**
     * Helper method to close the Fragment or its hosting Activity.
     */
    private void closeFragmentOrActivity() {
        if (getParentFragmentManager().getBackStackEntryCount() > 0) {
            getParentFragmentManager().popBackStack(); // 如果在回退栈中有Entry，则弹出
        } else if (getActivity() != null) {
            getActivity().finish(); // 否则关闭所在的Activity
        }
    }

    private void updateTime() {
        SimpleDateFormat sdf = new SimpleDateFormat("HH:mm", Locale.getDefault());
        String currentTime = sdf.format(new Date());
        tvTime.setText(currentTime);
    }

    private void saveAsDraft() {
        String title = etCourseTitle.getText().toString().trim();
        String description = etCourseDescription.getText().toString().trim();

        if (title.isEmpty()) {
            // 核心变化 4: 使用 getContext() 或 getActivity() 作为 Toast 的上下文
            Toast.makeText(getContext(), "请输入课程标题", Toast.LENGTH_SHORT).show();
            return;
        }

        Toast.makeText(getContext(), "课程已保存为草稿", Toast.LENGTH_SHORT).show();
    }

    private void addNewChapter() {
        // 使用保存的 LayoutInflater 来加载布局
        View chapterView = fragmentInflater.inflate(R.layout.item_chapter, chapterContainer, false);

        int chapterCount = chapterContainer.getChildCount() + 1;
        TextView tvChapterTitle = chapterView.findViewById(R.id.tv_chapter_title);
        tvChapterTitle.setText("第" + chapterCount + "章 新章节");

        setupChapterListeners(chapterView);

        chapterContainer.addView(chapterView);

        Toast.makeText(getContext(), "新章节已添加", Toast.LENGTH_SHORT).show();
    }

    private void setupChapterListeners(View chapterView) {
        ImageButton btnUp = chapterView.findViewById(R.id.btn_chapter_up);
        ImageButton btnDown = chapterView.findViewById(R.id.btn_chapter_down);
        ImageButton btnDelete = chapterView.findViewById(R.id.btn_chapter_delete);
        Button btnAddSection = chapterView.findViewById(R.id.btn_add_section);
        LinearLayout sectionContainer = chapterView.findViewById(R.id.section_container);

        btnUp.setOnClickListener(v -> moveChapterUp(chapterView));
        btnDown.setOnClickListener(v -> moveChapterDown(chapterView));
        btnDelete.setOnClickListener(v -> deleteChapter(chapterView));
        btnAddSection.setOnClickListener(v -> addNewSection(sectionContainer));
    }

    private void moveChapterUp(View chapterView) {
        int position = chapterContainer.indexOfChild(chapterView);
        if (position > 0) {
            chapterContainer.removeViewAt(position);
            chapterContainer.addView(chapterView, position - 1);
            updateChapterNumbers();
        }
    }

    private void moveChapterDown(View chapterView) {
        int position = chapterContainer.indexOfChild(chapterView);
        if (position < chapterContainer.getChildCount() - 1) {
            chapterContainer.removeViewAt(position);
            chapterContainer.addView(chapterView, position + 1);
            updateChapterNumbers();
        }
    }

    private void deleteChapter(View chapterView) {
        chapterContainer.removeView(chapterView);
        updateChapterNumbers();
        Toast.makeText(getContext(), "章节已删除", Toast.LENGTH_SHORT).show();
    }

    private void updateChapterNumbers() {
        for (int i = 0; i < chapterContainer.getChildCount(); i++) {
            View chapterView = chapterContainer.getChildAt(i);
            TextView tvChapterTitle = chapterView.findViewById(R.id.tv_chapter_title);
            String currentText = tvChapterTitle.getText().toString();
            String chapterName = currentText.replaceAll("第\\d+章", "").trim();
            tvChapterTitle.setText("第" + (i + 1) + "章 " + chapterName);
        }
    }

    private void addNewSection(LinearLayout sectionContainer) {
        // 使用保存的 LayoutInflater 来加载布局
        View sectionView = fragmentInflater.inflate(R.layout.item_section, sectionContainer, false);

        int sectionCount = sectionContainer.getChildCount() + 1;
        TextView tvSectionTitle = sectionView.findViewById(R.id.tv_section_title);

        View chapterView = (View) sectionContainer.getParent();
        TextView tvChapterTitle = chapterView.findViewById(R.id.tv_chapter_title);
        String chapterText = tvChapterTitle.getText().toString();
        int chapterNumber = extractChapterNumber(chapterText);

        tvSectionTitle.setText(chapterNumber + "." + sectionCount + " 新小节");

        setupSectionListeners(sectionView, sectionContainer);

        sectionContainer.addView(sectionView);

        Toast.makeText(getContext(), "新小节已添加", Toast.LENGTH_SHORT).show();
    }

    private int extractChapterNumber(String chapterText) {
        try {
            String numberStr = chapterText.replaceAll("[^\\d]", "");
            return Integer.parseInt(numberStr);
        } catch (NumberFormatException e) {
            return 1;
        }
    }

    private void setupSectionListeners(View sectionView, LinearLayout sectionContainer) {
        ImageButton btnUp = sectionView.findViewById(R.id.btn_section_up);
        ImageButton btnDown = sectionView.findViewById(R.id.btn_section_down);
        ImageButton btnDelete = sectionView.findViewById(R.id.btn_section_delete);
        Button btnUploadVideo = sectionView.findViewById(R.id.btn_upload_video);
        Button btnUploadPPT = sectionView.findViewById(R.id.btn_upload_ppt);


        btnUp.setOnClickListener(v -> moveSectionUp(sectionView, sectionContainer));
        btnDown.setOnClickListener(v -> moveSectionDown(sectionView, sectionContainer));
        btnDelete.setOnClickListener(v -> deleteSection(sectionView, sectionContainer));
        btnUploadVideo.setOnClickListener(v -> uploadVideo(sectionView));
        btnUploadPPT.setOnClickListener(v -> uploadPPT(sectionView));

    }

    private void moveSectionUp(View sectionView, LinearLayout sectionContainer) {
        int position = sectionContainer.indexOfChild(sectionView);
        if (position > 0) {
            sectionContainer.removeViewAt(position);
            sectionContainer.addView(sectionView, position - 1);
            updateSectionNumbers(sectionContainer);
        }
    }

    private void moveSectionDown(View sectionView, LinearLayout sectionContainer) {
        int position = sectionContainer.indexOfChild(sectionView);
        if (position < sectionContainer.getChildCount() - 1) {
            sectionContainer.removeViewAt(position);
            sectionContainer.addView(sectionView, position + 1);
            updateSectionNumbers(sectionContainer);
        }
    }

    private void deleteSection(View sectionView, LinearLayout sectionContainer) {
        sectionContainer.removeView(sectionView);
        updateSectionNumbers(sectionContainer);
        Toast.makeText(getContext(), "小节已删除", Toast.LENGTH_SHORT).show();
    }

    private void updateSectionNumbers(LinearLayout sectionContainer) {
        View chapterView = (View) sectionContainer.getParent();
        TextView tvChapterTitle = chapterView.findViewById(R.id.tv_chapter_title);
        String chapterText = tvChapterTitle.getText().toString();
        int chapterNumber = extractChapterNumber(chapterText);

        for (int i = 0; i < sectionContainer.getChildCount(); i++) {
            View sectionView = sectionContainer.getChildAt(i);
            TextView tvSectionTitle = sectionView.findViewById(R.id.tv_section_title);
            String currentText = tvSectionTitle.getText().toString();
            String sectionName = currentText.replaceAll("\\d+\\.\\d+", "").trim();
            tvSectionTitle.setText(chapterNumber + "." + (i + 1) + " " + sectionName);
        }
    }

    private void uploadVideo(View sectionView) {
        Toast.makeText(getContext(), "上传视频功能", Toast.LENGTH_SHORT).show();
    }

    private void uploadPPT(View sectionView) {
        Toast.makeText(getContext(), "上传PPT功能", Toast.LENGTH_SHORT).show();
    }

    private void setPreviewSettings(View sectionView) {
        Toast.makeText(getContext(), "试看设置功能", Toast.LENGTH_SHORT).show();
    }

    private void saveCourse() {
        String title = etCourseTitle.getText().toString().trim();
        String description = etCourseDescription.getText().toString().trim();

        if (title.isEmpty()) {
            Toast.makeText(getContext(), "请输入课程标题", Toast.LENGTH_SHORT).show();
            return;
        }

        if (description.isEmpty()) {
            Toast.makeText(getContext(), "请输入课程描述", Toast.LENGTH_SHORT).show();
            return;
        }

        // 这里实现保存课程的完整逻辑
        // 包括收集所有章节和小节的数据

        Toast.makeText(getContext(), "课程保存成功", Toast.LENGTH_SHORT).show();

        // 核心变化 5: 成功后关闭 Fragment/Activity
        closeFragmentOrActivity();
    }
}